#port = '5556'  
import time,os
#import zmq
import cv2
import pyautogui
import numpy as np

from redis import StrictRedis
import time
import sys
import os
import numpy as np
import cv2
import socket

#---------------------------------
# please change the configuration
#---------------------------------
REDIS_HOST = '127.0.0.1'
REDIS_PORT = 6379
REDIS_PASS = 'xxxx'
IMG_KEY = 'image-fifo'
#------------------------------

RESIZE_RATIO = 1

#-------------------
# get_hostname
#-------------------
def get_hostname():
    return socket.getfqdn(socket.gethostname( ))

#-------------------
# to_strs
#-------------------
def to_strs(b_s):
    #print('to_strs:',type(b_s))
    if type(b_s) == str:
        return b_s
        
    elif type(b_s) == bytes:
        #print('is bytes')
        return b_s.decode(encoding = 'utf8')
        
    else:
        return b_s

#-------------------
# to_bytes
#-------------------
def to_bytes(b_s):
    if type(b_s) == bytes:
        return b_s
        
    elif type(b_s) == str:
        #print('is str')
        return b_s.encode(encoding = 'utf8')
        
    else:
        return b_s

#-------------------
# readfile
#-------------------
def readfile(filename):
    f = open(filename,'rb')
    fs = f.read()
    fs = fs.decode('utf-8')
    f.close()
    return fs

#-------------------
# readfile2
#-------------------
def readfile2(filename):
    f = open(filename,'rb')
    fs = f.read()
    f.close()
    return fs

def writefile(filename,content):
    f = open(filename,'wb')
    if type(content) == str:
        content_bytes = content.encode('utf-8')
        f.write(content_bytes)
    else:
        f.write(content)
    f.close()
    return

#-------------------
# writefile2
#-------------------
def writefile2(filename,content):
    f = open(filename,'ab')
    if type(content) == str:
        content_bytes = content.encode('utf-8')
        f.write(content_bytes)
    else:
        f.write(content)
    f.flush()
    f.close()
    return
    
#-------------------
# has_file
#-------------------
def has_file(filename):
    if os.path.exists(filename):
        return True
    else:
        return False

#-------------------
# get_file_size
#-------------------        
def get_file_size(fname):
    if has_file(fname):
        statinfo = os.stat(fname)
        return statinfo.st_size
    else:
        return 0
        

#-------------------
# is_linux
#-------------------        
def is_linux():
    sysstr = platform.system()
    if(sysstr =="Windows"):
        return False
    elif(sysstr == "Linux"):
        return True
    else:
        return False

#-------------------
# remove_file
#-------------------
def remove_file(filename):
    if os.path.exists(filename):
        os.remove(filename)

#-------------------
# log_dump
#-------------------
def log_dump(filename,content):
    if get_file_size(filename) < 1024*1024*100:
        fpath = filename
        f = open(filename,'ab')
        t_s = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
        content = t_s + '->' + str(content) + '\r\n'
        if type(content) == str:
            content_bytes = content.encode('utf-8')
            f.write(content_bytes)
        else:
            f.write(content)
        f.close()
        
#-------------------
# screen_snapshot
#-------------------        
def screen_snapshot():
    img = pyautogui.screenshot() # x,y,w,h
    # img.save('screenshot.png')
    frame = cv2.cvtColor(np.asarray(img),cv2.COLOR_RGB2BGR)
    frame = cv2.resize(frame,(int(frame.shape[1]/RESIZE_RATIO),int(frame.shape[0]/RESIZE_RATIO)))
    #cv2.imwrite('temp.jpg',frame)
    _, encoded_frame = cv2.imencode('.jpg', frame)
    #cv2.imshow('title',enc)    
    #cv2.waitKey()
    #print('encoded_frame:',type(encoded_frame))
    fname = str(int(time.time()*1000)) + '.jpg' + '\r\n' 
    return to_bytes(fname) + encoded_frame.tobytes()
        

#=============================================================================================   
#----------------------
# main
#----------------------
VER = '@2022.5.15'    
if __name__ == '__main__':

    IMG_KEY = get_hostname()
    print('IMG_KEY:',IMG_KEY)

    while True:
        try:
            if REDIS_PASS == '':
                r = StrictRedis(host=REDIS_HOST, port=REDIS_PORT, db=0)
            else:
                r = StrictRedis(host=REDIS_HOST, port=REDIS_PORT, db=0, password=REDIS_PASS)

            expected_time = time.time() + 60
            last_name = ''
            
            r.hset('screen_vi',IMG_KEY,str(time.time()))

            while True:
                try:
                    if (time.time() >= expected_time):
                        expected_time = time.time() + 60          
                        b = screen_snapshot()
                        ret = r.rpush(IMG_KEY,b)
                        print('ret:',ret)
                        time.sleep(1)

                    else:
          
                        time.sleep(1)
                    
                except Exception as e:
                    print('exception:',str(e))
                    try:
                        r.close()
                    except:
                        pass
                        
                    if REDIS_PASS == '':
                        r = StrictRedis(host=REDIS_HOST, port=REDIS_PORT, db=0)
                    else:
                        r = StrictRedis(host=REDIS_HOST, port=REDIS_PORT, db=0, password=REDIS_PASS)
        
        except Exception as e:
            time.sleep(1)
            pass
            
                            